<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="60%">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120">
      <el-row>
        <el-col :span="8">
          <el-form-item label="所属企业" prop="colliery">
            <el-select clearable filterable style="width: 100%" v-model="formData.colliery" placeholder="请选择所属企业"
              @change="collieryChange">
              <el-option v-for="item in companyList" :key="item.id" :label="item.tenantName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="煤种名称" prop="coal">
            <el-select clearable filterable style="width: 100%" v-model="formData.coal" placeholder="请选择煤种名称"
              :disabled="!formData.colliery">
              <el-option v-for="item in coalTypeList" :key="item.id" :label="item.coalName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="坑口价" prop="pitPrice">
            <el-input :maxlength="20" v-model="formData.pitPrice" :disabled="formData.platformSource!=3"
              placeholder="请输入坑口价" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="热值" prop="calorificValue">
            <el-input :maxlength="20" v-model="formData.calorificValue" placeholder="请输入热值" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="硫" prop="sulfur">
            <el-input :maxlength="20" v-model="formData.sulfur" placeholder="请输入硫" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="灰" prop="ash">
            <el-input :maxlength="20" v-model="formData.ash" placeholder="请输入灰" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="全水" prop="allWater">
            <el-input :maxlength="20" v-model="formData.allWater" placeholder="请输入全水" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="内水" prop="mad">
            <el-input :maxlength="20" v-model="formData.mad" placeholder="请输入内水" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="灰熔点" prop="ashFusionPoint">
            <el-input :maxlength="20" v-model="formData.ashFusionPoint" placeholder="请输入灰熔点" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="可磨指数" prop="grindabilityIndex">
            <el-input :maxlength="20" v-model="formData.grindabilityIndex" placeholder="请输入可磨指数" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="焦渣特征" prop="panBreeze">
            <el-input :maxlength="20" v-model="formData.panBreeze" placeholder="请输入焦渣特征" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="挥发分" prop="volatileMatter">
            <el-input :maxlength="20" v-model="formData.volatileMatter" placeholder="请输入挥发分" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="价格时间" prop="priceTime">
            <el-date-picker v-model="formData.priceTime" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm"
              placeholder="请选择价格时间" type="datetime" :disabled="true" style="width:100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="数据来源" prop="platformSource">
            <el-select clearable style="width: 100%" v-model="formData.platformSource" :disabled="true"
              placeholder="请选择数据来源">
              <el-option v-for="item in getIntDictOptions(DICT_TYPE.PLATFORM_SOURCE)" :key="item.value"
                :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="化验报告" prop="assayReport">
            <UploadImg v-model="formData.assayReport" :limit="1" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
  import { cloneDeep } from 'lodash'
  import * as coalMarket from '@/api/coalMarket'
  import { formatDate } from '@/utils/formatTime'
  import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'

  const emit = defineEmits(['success'])
  const rowId = ref()
  const formRef = ref()
  const formLoading = ref(false)
  const dialogVisible = ref(false)
  const message = useMessage()
  const dialogTitle = ref()
  const companyList = ref([])
  const coalTypeList = ref([])
  const formData = ref({
    colliery: undefined,
    coal: undefined,
    pitPrice: undefined,
    calorificValue: undefined,
    sulfur: undefined,
    ash: undefined,
    allWater: undefined,
    mad: undefined,
    ashFusionPoint: undefined,
    grindabilityIndex: undefined,
    panBreeze: undefined,
    volatileMatter: undefined,
    priceTime: undefined,
    platformSource: 3,
    assayReport: undefined,
  })

  const formRules = reactive({
    colliery: [{ required: true, message: '请选择所属企业', trigger: 'change' }],
    coal: [{ required: true, message: '请选择煤种名称', trigger: 'change' }],
    pitPrice: [{ required: true, message: '请输入坑口价', trigger: 'blur' }],
    calorificValue: [{ required: true, message: '请输入热值', trigger: 'blur' }],
    sulfur: [{ required: true, message: '请输入硫', trigger: 'blur' }],
    priceTime: [{ required: true, message: '请选择价格时间', trigger: 'change' }],
  })

  const open = async (id) => {
    resetForm()
    dialogVisible.value = true
    rowId.value = id
    if (id) {
      dialogTitle.value = '编辑'
    } else {
      dialogTitle.value = '新增'
    }
    getCompanyList()
    if (id) {
      getPriceMgrById(id)
    }
  }

  const resetForm = () => {
    Object.keys(formData.value).forEach(key => {
      if (key === 'platformSource') {
        formData.value[key] = 3
      } else if (key === 'priceTime') {
        formData.value[key] = formatDate(new Date(), 'YYYY-MM-DD HH:mm')
      } else {
        formData.value[key] = undefined
      }
    })
  }

  const collieryChange = () => {
    coalTypeList.value = []
    formData.value.coal = undefined
    if (!formData.value.colliery) {
      return
    }
    getCoalByCompanyId()
  }

  const getCompanyList = async () => {
    const res = await coalMarket.getCompanyList()
    companyList.value = res || []
  }

  const getCoalByCompanyId = async () => {
    const res = await coalMarket.getCoalByCompanyId({
      companyId: formData.value.colliery
    })
    coalTypeList.value = res || []
  }

  // const getCollieryMgrList = async () => {
  //   const res = await coalMarket.getCollieryMgrList()
  //   coalTypeList.value = res || []
  // }

  const getPriceMgrById = async (id) => {
    const res = await coalMarket.getPriceMgrById({ id })
    Object.keys(formData.value).forEach(key => {
      if (key === 'colliery') {
        formData.value[key] = companyList.value.find(e => {
          if (e.tenantId) {
            return e.tenantId.toString() === res.collieryId && e.tenantName === res.collieryName
          } else {
            return e.tenantName === res.collieryName
          }
        })?.id
        getCoalByCompanyId()
      } else if (key === 'coal') {
        formData.value[key] = coalTypeList.value.find(e => e.coalId === res.coalId && e.coalName === res.coalName)?.id
      } else {
        formData.value[key] = res[key]
      }
    })
  }

  const submitForm = async () => {
    console.log('formData.value', formData.value)
    if (!formRef) return
    const valid = await formRef.value.validate()
    if (!valid) return
    formLoading.value = true
    if (rowId.value) {
      updatePriceMgrInfo()
    } else {
      createPriceMgrInfo()
    }
  }

  const createPriceMgrInfo = async () => {
    try {
      const data = cloneDeep(formData.value)
      data['collieryId'] = companyList.value.find(e => e.id === data.colliery)?.tenantId
      data['collieryName'] = companyList.value.find(e => e.id === data.colliery)?.tenantName
      data['coalId'] = coalTypeList.value.find(e => e.id === data.coal)?.coalId
      data['coalName'] = coalTypeList.value.find(e => e.id === data.coal)?.coalName
      delete data.colliery
      delete data.coal
      const res = await coalMarket.createPriceMgrInfo(data)
      if (res) {
        message.success('新增成功')
        emit('success')
        dialogVisible.value = false;
      }
    } finally {
      formLoading.value = false
    }
  }

  const updatePriceMgrInfo = async () => {
    try {
      const data = cloneDeep(formData.value)
      data['id'] = rowId.value
      data['collieryId'] = companyList.value.find(e => e.id === data.colliery)?.tenantId
      data['collieryName'] = companyList.value.find(e => e.id === data.colliery)?.tenantName
      data['coalId'] = coalTypeList.value.find(e => e.id === data.coal)?.coalId
      data['coalName'] = coalTypeList.value.find(e => e.id === data.coal)?.coalName
      delete data.colliery
      delete data.coal
      const res = await coalMarket.updatePriceMgrInfo(data)
      if (res) {
        message.success('编辑成功')
        emit('success')
        dialogVisible.value = false;
      }
    } finally {
      formLoading.value = false
    }
  }

  defineExpose({ open })
</script>
<style lang="scss" scoped>
  :deep(.el-input__wrapper) {
    width: 100%
  }
</style>